package com.g.base.databind

import android.databinding.BindingAdapter
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.g.base.R
import com.g.base.extend.setSpace
import com.g.base.help.glide.GlideCircleTransform
import com.g.base.help.glide.GlideRoundTransform


/**
 * Created by G on 2017/8/12 0012.
 */
//设置视图宽高
@BindingAdapter("android:layout_height", "android:layout_width", requireAll = false)
fun setLayoutSpace(view: View, height: Number? = null, width: Number? = null) {
    view.setSpace(height, width)
}

@BindingAdapter("android:src")
fun setImageViewResource(imageView: ImageView, resource: Int) {
    imageView.setImageResource(resource)
}

@BindingAdapter("android:background")
fun setViewBackground(view: View, resource: Int) {
    view.setBackgroundResource(resource)
}

@BindingAdapter("android:backgroundTint")
fun setBackgroundTint(view: View, resource: Int) {
    if (resource != 0)
        view.backgroundTintList = view.resources.getColorStateList(resource)
    else
        view.backgroundTintList = null
}

//设置背景图片 圆角 OR 圆形图片 OR 默认图片
@BindingAdapter("app:image", "app:imageRadius", "app:imageCircle", "app:placeholder", "app:error", requireAll = false)
fun setBackgroundImage(view: ImageView, oldSrc: Any? = null, oldRadius: Number? = null, oldCircle: Boolean? = null, oldPlaceholder: Int? = null, oldError: Int? = null,
                       src: Any? = null, radius: Number? = null, circle: Boolean? = null, placeholder: Int? = null, error: Int? = null) {

    if (oldSrc == src) return
    val glide = Glide.with(view.context)
    val url = if (src is String && src.startsWith("//")) "http:$src" else src
    glide.load(url)
            .placeholder(placeholder ?: R.drawable.load_placeholder)
            .error(error ?: R.drawable.load_error)
            .apply {
                if (circle != null && circle) {
                    transform(GlideCircleTransform(view.context))
                } else if (radius != null && radius.toInt() > 0) {
                    transform(GlideRoundTransform(view.context, radius.toInt()))
                } else {
                    dontTransform()
                }
                crossFade(300)
                into(view)
            }
}